import com.spider.admin.utils.CommonUtil;
import com.spider.admin.utils.OSCommandUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class NginxConfigValidator {


    /**
     * @desc 执行cmd命令
     */
    private String executeCmd(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("cmd /c " + command);
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
        String line = null;
        StringBuilder build = new StringBuilder();
        while ((line = br.readLine()) != null) {
            build.append(line);
        }
        return build.toString();
    }

    /**
     * 获取Nginx代理系统目录和可执行文件
     *
     * @return
     */
    public static String[] findAgentExeFile() {
        String[] strs = new String[2];
        strs[0] = "D:\\spider\\spider-agent";
        ;
        if (OSCommandUtil.isWinOS()) {
            strs[1] = "nginx.exe";
        } else {
            strs[0] = strs[0] + "\\bin";
            strs[1] = "openrestry";
        }
        Path filePath = Paths.get(strs[0], strs[1]);
        boolean bol = Files.exists(filePath);
        if (bol) {
            return strs;
        } else {
            return null;
        }
    }

    /**
     * 开启windows系统的nginx
     *
     * @throws IOException
     */
    public static void startWinProc() throws Exception {
        String agentExe = "cmd /c nginx -t -c D:\\spider\\spider-agent\\confTest\\nginx.conf";
        String[] agentServerPaths = findAgentExeFile();
        if (agentServerPaths != null && agentServerPaths.length == 2) {
            String CONFPREFIXURL = agentServerPaths[0];

            File dir = new File(CONFPREFIXURL);
            String[] str = new String[]{};
            // 执行命令
            Process process = Runtime.getRuntime().exec(agentExe, str, dir);

            BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
            String line = null;
            StringBuilder build = new StringBuilder();
            while ((line = br.readLine()) != null) {
                build.append(line);
            }


            // 输出或者检查输出结果来判断配置是否有效
            System.out.println("=====" + build.toString() + "=====");

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                // 配置文件有效
                System.out.println("=====OK=====");
            } else {
                // 配置文件无效
                System.out.println("=====ERROR=====");
            }
        } else {
            throw new Exception("未找到启动文件");
        }
    }

    public static boolean validateNginxConfig(String nginxConfigPath) {
        nginxConfigPath = "D:\\spider\\spider-agent\\confTest\\nginx.conf";
        ProcessBuilder processBuilder = new ProcessBuilder("nginx", "-t", "-c", nginxConfigPath);
        processBuilder.redirectErrorStream(true);

        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                // 输出或者检查输出结果来判断配置是否有效
                System.out.println("=====" + line + "=====");
            }

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                // 配置文件有效
                return true;
            } else {
                // 配置文件无效
                return false;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
//        String configPath = findAgentExeFile()[0];
        startWinProc();
//        validateNginxConfig(null);
    }
}